package com.ls.fw.data.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.ls.fw.data.bean.Record;
import com.ls.fw.data.bean.Table;
import com.ls.fw.data.enums.AFunctions;
import com.ls.fw.data.exception.DataException;
import com.ls.fw.data.handler.SqlParser;
import com.ls.fw.data.mapper.RowMapper;
import com.ls.fw.data.mapper.ScanRowMapper;
import com.ls.fw.data.result.DataResult;
import com.ls.fw.data.result.DataResultSet;
import com.ls.fw.data.result.DataResultSetImpl;
import com.ls.fw.data.statement.Insert;
import com.ls.fw.data.statement.Select;
import com.ls.fw.data.statement.Update;




/**
 * 数据访问接口适配器
 * @author ls
 * 2014年12月13日下午3:39:49
 */
public abstract class DaoAdapter extends ControlDataDaoAdapter implements Dao{
	
	
	@Override
	public boolean exist(Select select) {
		select.getFields().clear();
		select.addMethodField(AFunctions.COUNT).setName("*");
		return this.search(select).getTotal()>0;
	} 
	
	@Override
	public boolean insert(Insert insert) {
		return this.insert(insert, true);
	}

	@Override
	public boolean update(Update update) {
		return this.update(update, false);
	}
	
	@Override
	public <T> List<T> search(Select select, RowMapper<T> rowMapper) {
		DataResult result = this.search(select);
		DataResultSet set = new DataResultSetImpl(result);
		List<T> list = new ArrayList<T>(result.getSize());
		try {
			int index = 1;
			while(set.next()){
				T t = rowMapper.mapRow(set,index++);
				if(t != null){
					list.add(t);
				}
			}
		} catch (SQLException e) {
			throw new DataException(e.getMessage(),e.getCause());
		} finally{
			if(set!=null){
				try {
					set.close();
				} catch (SQLException e) {
				}
			}
			result = null;
		}
		return list;
	}
	
	@Override
	public DataResultSet executeQuery(Select select) {
		DataResult result = this.search(select);
		return new DataResultSetImpl(result);
	}

	/**
	 * 添加表结构
	 * @author ls
	 * 2014年12月3日下午5:04:38 
	 * @param table
	 * @return
	 */
	public boolean create(Table table){
		return true;
	}
	
	
	/**
	 * 修改表结构
	 * @author ls
	 * 2014年12月3日下午5:04:47 
	 * @param table
	 * @return
	 */
	public boolean update(Table table){
		return true;
	}
	
	
	/**
	 * 删除表结构
	 * @author ls
	 * 2014年12月3日下午5:04:56 
	 * @param table
	 * @return
	 */
	public boolean drop(Table table){
		return true;
	}

	@Override
	public long load(Table fromTable, Select select, Table toTable,
			boolean deleteOldData, ScanRowMapper<Record> rowMapper)
			throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	public SqlParser getSqlParser(){
		return null;
	}
	
	public	Table getTable(String name){
		return null;
	}
}
